<?php

	//Ex.: print_array(array(array("id" => 1, "name" => "nombre"), ... ));
	function print_array($arr){
		echo '<pre>'.nl2br(print_r($arr,true)).'</pre>';
	}

	//Ex.: leer("SELECT * FROM <table>");
	function leer($sql){
		try{
			$resEmp = $GLOBALS['db']->query($sql);
			$count = 0;
			$result = array();
			if ($resEmp->rowCount()> 0) {
				while ($rowEmp = $resEmp->fetch()) {
			  		$result[$count] = $rowEmp;
					$count++;
				}
			}
			return $result;
		}catch(PDOException $e){
			echo 'Falló la conexión: ' . $e->getMessage();
		}

	}

	//Ex.: insertar("usuario", array("name" => "nombre", "surname1" => "apellido1", "surname2" => "apellido2", ... ));
	function insertar($table, $values, $i=false, $tipo_tabla=""){

		if($tipo_tabla == "RELACIONAL")
			$v = "('".(implode("','",$values))."')";
		else
			$v = "('','".(implode("','",$values))."')";

		$sql = "INSERT INTO ".$table." VALUES ".$v;
		echo '$sql: '.$sql.'<br>';
		try{
			$res = $GLOBALS['db']->exec($sql);
				if($i)
					return $GLOBALS['db']->lastInsertId();//mysql_insert_id();
		}catch(PDOException $e){
			return -1;
			echo 'Falló la conexión: ' . $e->getMessage();
		}
		
	}

	//Ex.: modificar("usuario", array("id" => 1, "name" => "nombre"));
	function modificar($table,$data){
		$values = "";
		foreach($data as $key => $data){

			if($values==""){

				$where = $key." = '".$data."'";
				$values .= "SET ";

			}elseif($values=="SET ")
				$values .= $key." = '".$data."'";
			else 
				$values .= ", ".$key." = '".$data."'";
		}

		$operation = "UPDATE ".$table." ".$values." WHERE ".$where;
		try{
			$GLOBALS['db']->execute($operation);//mysql_query($operation,$GLOBALS['db']) or die(mysql_error());
		}catch(PDOException $e){
			echo 'Falló la conexión: ' . $e->getMessage();
		}
		
	}

	//Ex.: eliminar("usuario", "id", 2);
	function eliminar($table, $nombre, $valor){

		$sql = "DELETE FROM ".$table." WHERE ".$nombre." = ".$valor;
		try{
			$GLOBALS['db']->execute($sql);//mysql_query($sql,$GLOBALS['conexion']) or die(mysql_error());
		}catch(PDOException $e){
			echo 'Falló la conexión: ' . $e->getMessage();
		}
	}


?>
